package oj_leetcode;

public class MultiplyStrings {
    public String multiply(String num1, String num2) {
        if (num2.equals("0") || num1.equals("0")) {
            return "0";
        }
        String result = "";
        for (int i = 0; i < num2.length(); i++) {
            // todo java中字符串转对应整数的所有方法
            int curr = num2.charAt(i) - '0';
            // 计算该位上的数字和1串相乘的结果
            String res = "";
            int carry = 0;
            for (int j = num1.length() - 1; j >= 0; j--) {
                int pos = num1.charAt(j) - '0';
                int value = curr * pos + carry;
                res = value % 10 + res;
                carry = value / 10;
            }
            if (carry > 0) {
                res = carry + res;
            }
            // 最后要在结果字符串后面加上i个0
            for (int j = 0; j < num2.length() - 1 - i; j++) {
                res = res + "0";
            }

            // 合并当前的result和res
            int m = 0, n = 0;
            carry = 0;
            String tmp = "";

            while (m < res.length() || n < result.length()) {
                // todo 是否可以改进这里的循环和条件判断的重复
                int resCurr = 0;
                int resultCurr = 0;
                if (m < res.length()) {
                    resCurr = res.charAt(res.length() - 1 - m) - '0';
                }
                if (n < result.length()) {
                    resultCurr = result.charAt(result.length() - 1 - n) - '0';
                }
                int termV = resCurr + resultCurr + carry;

                tmp = termV % 10 + tmp;
                carry = termV / 10;
                m++;
                n++;
            }
            if (carry > 0) {
                tmp = carry + tmp;
            }
            result = tmp;
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(new MultiplyStrings().multiply("140", "721"));
    }
}
